package com.xtedu.examproject.controller;

import com.xtedu.examproject.entity.*;
import com.xtedu.examproject.service.CourseService;
import com.xtedu.examproject.service.SubjectService;
import com.xtedu.examproject.util.CommonUtils;
import com.xtedu.examproject.util.PageHelper;
import com.xtedu.examproject.util.RedisUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/coursemanage/*")
public class CourseServlet extends HttpServlet {
    private CourseService courseService;
    private SubjectService subjectService;
    private final static int pageSize = 5; // 每页显示5条记录

    public void init() {
        courseService = new CourseService();
        subjectService = new SubjectService();
    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        resp.setContentType("text/html;charset=UTF-8");

        // 获取路径信息
        String pathInfo = req.getPathInfo();
        // 处理路径信息
        String path = (pathInfo == null || pathInfo.equals("/") || pathInfo.equals("")) ? "/" : pathInfo;
        try {
            switch (path) {
                case "/addcourse":
                    showAddCoursePage(req, resp);
                    break;
                case "/delete":
                    deleteCourse(req, resp);
                    break;
                case "/search":
                    searchCourses(req, resp);
                    break;
                case "/update":
                    showUpdateCoursePage(req, resp);
                    break;
                case "/sort":
                    showSortCourse(req, resp);
                    break;
                case "/getCourseTeachers":
                    getCourseTeachers(req, resp);
                    break;
                case "/getAvailableTeachers":
                    getAvailableTeachers(req, resp);
                    break;
                case "/findAll":
                    findAll(req, resp);
                    break;
                default:
                    showCourseManagePage(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            handleException(req, resp, e, "加载页面失败: " + e.getMessage(), "/WEB-INF/views/coursemanage.jsp");
        }
    }

    private void findAll(HttpServletRequest req, HttpServletResponse resp) {
        try {
            List<Course> courseList = courseService.findAllCourse();
            if (courseList == null) {
                CommonUtils.sendErrorResponse(resp, "没有找到课程信息");
                return;
            }
            CommonUtils.sendSuccessResponse(resp, "获取课程数据成功", courseList);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        // 获取路径信息
        String pathInfo = request.getPathInfo();

        try {
            if (pathInfo == null || pathInfo.equals("/") || pathInfo.equals("")) {
                showCourseManagePage(request, response);
            } else if (pathInfo.equals("/addcourse")) {
                // 处理添加课程表单提交
                addCourses(request, response);
            } else if (pathInfo.equals("/update")) {
                updateCourses(request, response);
            } else if (pathInfo.equals("/savesort")) {
                saveCourseSort(request, response);
            } else if (pathInfo.equals("/addTeacherToCourse")) {
                addTeacherToCourse(request, response);
            } else if (pathInfo.equals("/removeCourseTeacher")) {
                removeCourseTeacher(request, response);
            } else {
                showCourseManagePage(request, response);
            }
        } catch (Exception e) {
            System.err.println("处理POST请求时发生错误: " + e.getMessage());
            e.printStackTrace();
            handleException(request, response, e, "操作失败: " + e.getMessage(), "/WEB-INF/views/addcourse.jsp");
        }
    }

    /**
     * 统一异常处理方法
     *
     * @param request
     * @param response
     * @param e
     * @param errorMessage
     * @param viewPath
     * @throws ServletException
     * @throws IOException
     */
    private void handleException(HttpServletRequest request, HttpServletResponse response,
                                 Exception e, String errorMessage, String viewPath)
            throws ServletException, IOException {
        request.setAttribute("error", errorMessage);

        // 检查响应是否已经提交
        if (response.isCommitted()) {
            // 如果响应已经提交，记录错误
            System.err.println("响应已提交，无法转发到错误页面: " + errorMessage);
        } else {
            // 如果响应未提交，尝试转发到错误页面
            try {
                request.getRequestDispatcher(viewPath).forward(request, response);
            } catch (IllegalStateException ex) {
                // 如果转发失败，尝试重定向
                System.err.println("转发失败，尝试重定向: " + ex.getMessage());
                try {
                    if (!response.isCommitted()) {
                        response.sendRedirect(request.getContextPath() + "/coursemanage/");
                    }
                } catch (IllegalStateException ex2) {
                    System.err.println("重定向也失败了: " + ex2.getMessage());
                }
            }
        }
    }


    /**
     * 显示课程管理页面（进行分页）
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void showCourseManagePage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            System.out.println("进入showCourseManagePage");
            int pageIndex = request.getParameter("pageIndex") != null ? Integer.parseInt(request.getParameter("pageIndex")) : 1;
            // 获取搜索参数
            String courseSearchText = request.getParameter("courseSearchText");
            String subjectSearchText = request.getParameter("subjectSearchText");

            // 获取当前登录用户
//            User user = (User) request.getSession().getAttribute("user");

//            HttpSession session =request.getSession();
//            User currentLogin= RedisUtil.getObject("session:"+session.getId(), User.class);

            PageHelper<Course> page = null;

            System.out.println("进入service方法");
            // 根据是否有搜索参数来决定查询方式
            if (courseSearchText != null && !courseSearchText.trim().isEmpty() &&
                    subjectSearchText != null && !subjectSearchText.trim().isEmpty()) {
                // 同时按课程名称和专业名称搜索
                courseSearchText = courseSearchText.trim();
                subjectSearchText = subjectSearchText.trim();
                page = courseService.findCoursesByCourseAndSubjectName(
                        courseSearchText, subjectSearchText, pageIndex, pageSize);
            } else if (courseSearchText != null && !courseSearchText.trim().isEmpty()) {
                // 按课程名称搜索
                courseSearchText = courseSearchText.trim();
                page = courseService.findPageSelectByCourseName(courseSearchText, pageIndex, pageSize);
            } else if (subjectSearchText != null && !subjectSearchText.trim().isEmpty()) {
                // 按专业名称搜索
                subjectSearchText = subjectSearchText.trim();
                page = courseService.findPageSelectBySubjectName(subjectSearchText, pageIndex, pageSize);
            } else {
                // 如果没有搜索条件，显示所有课程
//                page = courseService.findPageSelectByRoleId(pageIndex, pageSize, currentLogin.getId());
                page = courseService.findAll(pageIndex, pageSize);
            }

            System.out.println(page);
            System.out.println(page.getItems());
            String servletName = request.getPathInfo() != null ? request.getServletPath() + request.getPathInfo() : request.getServletPath();
            page.setServletName(servletName);

            // 保存分页结果
            request.setAttribute("page", page);
            // 保存搜索参数用于页面显示和分页链接
            request.setAttribute("courseSearchText", courseSearchText);
            request.setAttribute("subjectSearchText", subjectSearchText);

            List<Subject> subjects = subjectService.findAllSubject();
            request.setAttribute("subjects", subjects);

            request.getRequestDispatcher("/WEB-INF/views/coursemanage.jsp").forward(request, response);

        } catch (Exception e) {
            System.err.println("加载课程管理页面时发生错误: " + e.getMessage());
            e.printStackTrace();
            // 发生错误时检查响应是否已提交
            if (!response.isCommitted()) {
                // 如果响应未提交，尝试转发到错误页面
                request.setAttribute("error", "加载页面失败: " + e.getMessage());
                request.getRequestDispatcher("/WEB-INF/views/coursemanage.jsp").forward(request, response);
            } else {
                // 如果响应已提交，记录错误
                System.err.println("响应已提交，无法转发到错误页面: " + e.getMessage());
            }
        }
    }


    /**
     * 显示添加课程页面
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void showAddCoursePage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            List<Subject> subjects = subjectService.findAllSubject();
            request.setAttribute("subjects", subjects);
            request.getRequestDispatcher("/WEB-INF/views/addcourse.jsp").forward(request, response);
        } catch (Exception e) {
            System.err.println("加载添加课程页面时发生错误: " + e.getMessage());
            e.printStackTrace();
            // 发生错误时直接转发到错误页面
            request.setAttribute("error", "加载页面失败: " + e.getMessage());
            request.getRequestDispatcher("/WEB-INF/views/addcourse.jsp").forward(request, response);
        }
    }

    /**
     * 显示修改课程页面
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void showUpdateCoursePage(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取要更新的课程ID
            String courseIdStr = request.getParameter("id");

            if (courseIdStr != null && !courseIdStr.isEmpty()) {
                try {
                    int courseId = Integer.parseInt(courseIdStr);

                    // 获取课程信息
                    Course course = courseService.findById(courseId);

                    if (course != null) {
                        // 获取所有专业列表
                        List<Subject> subjects = subjectService.findAllSubject();

                        // 设置请求属性
                        request.setAttribute("course", course);
                        request.setAttribute("subjects", subjects);

                        // 转发到更新页面
                        request.getRequestDispatcher("/WEB-INF/views/updatecourse.jsp").forward(request, response);
                    } else {
                        // 课程不存在，显示错误信息
                        request.setAttribute("error", "课程不存在");
                        request.getRequestDispatcher("/WEB-INF/views/updatecourse.jsp").forward(request, response);
                    }
                } catch (NumberFormatException e) {
                    // ID参数格式错误
                    request.setAttribute("error", "无效的课程ID格式");
                    request.getRequestDispatcher("/WEB-INF/views/updatecourse.jsp").forward(request, response);
                }
            } else {
                // ID参数为空
                request.setAttribute("error", "无效的课程ID");
                request.getRequestDispatcher("/WEB-INF/views/updatecourse.jsp").forward(request, response);
            }
        } catch (Exception e) {
            System.err.println("加载修改课程页面时发生错误: " + e.getMessage());
            e.printStackTrace();
            // 发生错误时直接转发到错误页面
            request.setAttribute("error", "加载页面失败: " + e.getMessage());
            request.getRequestDispatcher("/WEB-INF/views/updatecourse.jsp").forward(request, response);
        }
    }


    /**
     * 处理添加课程
     *
     * @param request
     * @param response
     * @throws Exception
     */
    public void addCourses(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        // 接收添加课程信息
        String courseName = request.getParameter("course_name");
        String subjectId = request.getParameter("subject_id");
        String description = request.getParameter("description");
        System.out.println("课程名称: " + courseName);
        System.out.println("所属科目: " + subjectId);
        System.out.println("课程描述: " + description);

        // 进行数据的验证
        if (courseName == null || courseName.trim().isEmpty()
                || subjectId == null || subjectId.trim().isEmpty()
                || description == null || description.trim().isEmpty()) {

            // 重新加载科目列表
            List<Subject> subjects = subjectService.findAllSubject();
            request.setAttribute("subjects", subjects);
            request.setAttribute("course_name", courseName);
            request.setAttribute("subject_id", subjectId);
            request.setAttribute("description", description);
            request.setAttribute("error", "所有字段不能为空");

            request.getRequestDispatcher("/WEB-INF/views/addcourse.jsp").forward(request, response);
            return; // 验证失败时直接返回
        }

        // 创建Course对象并设置属性
        Course course = new Course();
        course.setName(courseName);
        try {
            course.setSubjectId(Integer.parseInt(subjectId));
        } catch (NumberFormatException e) {
            // 在这里添加调试信息
            System.out.println("subjectId转换失败: " + subjectId);
            // 重新加载科目列表
            List<Subject> subjects = subjectService.findAllSubject();
            request.setAttribute("subjects", subjects);
            request.setAttribute("course_name", courseName);
            request.setAttribute("description", description);
            request.setAttribute("error", "科目选择格式不正确");

            request.getRequestDispatcher("/WEB-INF/views/addcourse.jsp").forward(request, response);
            return;
        }
        // 设置课程描述
        course.setDescription(description);

        //设置课程状态默认开启
        course.setState(true);
        // 设置创建时间为当前时间
        course.setCreateDate(new Date(System.currentTimeMillis()));

        // 调用service层方法插入课程
        try {
            courseService.insertCourse(course);
            // 添加成功后重定向到课程管理页面并携带成功消息
            response.sendRedirect(request.getContextPath() + "/coursemanage/?success=" +
                    java.net.URLEncoder.encode("课程添加成功", "UTF-8"));
            //response.sendRedirect("/WEB-INF/views/coursemanage.jsp");
        } catch (Exception e) {
            System.out.println("添加课程失败: " + e.getMessage());
            // 重新加载科目列表
            List<Subject> subjects = subjectService.findAllSubject();
            request.setAttribute("subjects", subjects);
            request.setAttribute("course_name", courseName);
            request.setAttribute("subject_id", subjectId);
            request.setAttribute("description", description);
            request.setAttribute("error", "添加失败: " + e.getMessage());

            request.getRequestDispatcher("/WEB-INF/views/addcourse.jsp").forward(request, response);
        }
    }


    /**
     * 处理搜索课程
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void searchCourses(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取搜索参数
            String courseSearchText = request.getParameter("courseSearchText");
            String subjectSearchText = request.getParameter("subjectSearchText");
            int pageIndex = request.getParameter("pageIndex") != null ?
                    Integer.parseInt(request.getParameter("pageIndex")) : 1;

            System.out.println("课程搜索文本: " + courseSearchText);
            System.out.println("专业搜索文本: " + subjectSearchText);
            System.out.println("当前页码: " + pageIndex);

            // 构建重定向URL
            StringBuilder redirectUrl = new StringBuilder(request.getContextPath() + "/coursemanage/");

            boolean hasParams = false;

            if (courseSearchText != null && !courseSearchText.trim().isEmpty()) {
                if (!hasParams) {
                    redirectUrl.append("?");
                    hasParams = true;
                } else {
                    redirectUrl.append("&");
                }
                redirectUrl.append("courseSearchText=").append(java.net.URLEncoder.encode(courseSearchText.trim(), "UTF-8"));
            }

            if (subjectSearchText != null && !subjectSearchText.trim().isEmpty()) {
                if (!hasParams) {
                    redirectUrl.append("?");
                    hasParams = true;
                } else {
                    redirectUrl.append("&");
                }
                redirectUrl.append("subjectSearchText=").append(java.net.URLEncoder.encode(subjectSearchText.trim(), "UTF-8"));
            }

            if (pageIndex > 1) {
                if (!hasParams) {
                    redirectUrl.append("?");
                    hasParams = true;
                } else {
                    redirectUrl.append("&");
                }
                redirectUrl.append("pageIndex=").append(pageIndex);
            }

            request.getRequestDispatcher("/coursemanage").forward(request, response);
            // 使用重定向而不是转发
//            response.sendRedirect(redirectUrl.toString());

        } catch (Exception e) {
            System.err.println("搜索课程时发生错误: " + e.getMessage());
            e.printStackTrace();
            // 出错时重定向并携带错误信息
            try {
                if (!response.isCommitted()) {
                    String errorMessage = java.net.URLEncoder.encode("搜索失败: " + e.getMessage(), "UTF-8");
                    response.sendRedirect(request.getContextPath() + "/coursemanage/?error=" + errorMessage);
                }
            } catch (IllegalStateException ex) {
                System.err.println("重定向失败: " + ex.getMessage());
            }
        }
    }


    /**
     * 删除课程
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void deleteCourse(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 设置响应类型为JSON
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");

            // 获取要删除的课程ID
            String courseIdStr = request.getParameter("id");

            // 检查课程ID是否为空
            if (courseIdStr != null && !courseIdStr.isEmpty()) {
                try {
                    int courseId = Integer.parseInt(courseIdStr);

                    // 调用service层方法删除课程
                    boolean deleted = courseService.deleteCourseById(courseId);

                    // 返回JSON响应
                    if (deleted) {
                        response.getWriter().write("{\"success\":true,\"message\":\"课程删除成功\"}");
                    } else {
                        response.getWriter().write("{\"success\":false,\"message\":\"课程删除失败，可能课程不存在\"}");
                    }
                } catch (NumberFormatException e) {
                    response.getWriter().write("{\"success\":false,\"message\":\"课程ID格式错误\"}");
                }
            } else {
                response.getWriter().write("{\"success\":false,\"message\":\"无效的课程ID\"}");
            }
        } catch (Exception e) {
            System.err.println("删除课程时发生错误: " + e.getMessage());
            e.printStackTrace();

            // 返回JSON格式的错误响应
            try {
                response.getWriter().write("{\"success\":false,\"message\":\"删除课程失败: " + e.getMessage() + "\"}");
            } catch (Exception ex) {
                System.err.println("发送错误响应时发生异常: " + ex.getMessage());
            }
        } finally {
            try {
                response.getWriter().flush();
            } catch (Exception e) {
                // 忽略刷新异常
            }
        }
    }

    /**
     * 处理更新课程
     *
     * @param request
     * @param response
     * @throws Exception
     */
    public void updateCourses(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        System.out.println("进入updateCourses");

        // 接收更新课程信息
        String courseIdStr = request.getParameter("id");
        String courseName = request.getParameter("course_name");
        String subjectId = request.getParameter("subject_id");
        String description = request.getParameter("description");
        String stateStr = request.getParameter("state"); // 获取状态参数

        System.out.println("课程ID: " + courseIdStr);
        System.out.println("课程名称: " + courseName);
        System.out.println("所属科目: " + subjectId);
        System.out.println("课程描述: " + description);
        System.out.println("课程状态: " + stateStr);

        // 进行数据的验证
        if (courseIdStr == null || courseIdStr.trim().isEmpty() ||
                courseName == null || courseName.trim().isEmpty() ||
                subjectId == null || subjectId.trim().isEmpty() ||
                description == null || description.trim().isEmpty()) {

            // 重新加载科目列表
            List<Subject> subjects = subjectService.findAllSubject();
            request.setAttribute("subjects", subjects);
            request.setAttribute("error", "所有字段不能为空");

            // 重新获取课程信息并设置到request中
            if (courseIdStr != null && !courseIdStr.trim().isEmpty()) {
                    int courseId = Integer.parseInt(courseIdStr);
                    Course course = courseService.findById(courseId);
                    if (course != null) {
                        request.setAttribute("course", course);
                    }
            }
            request.getRequestDispatcher("/WEB-INF/views/updatecourse.jsp").forward(request, response);
            return; // 验证失败时直接返回
        }

        // 创建Course对象并设置属性
        Course course = new Course();
        try {
            course.setId(Integer.parseInt(courseIdStr));
            course.setName(courseName);
            course.setSubjectId(Integer.parseInt(subjectId));
            course.setDescription(description);

            // 处理状态字段
            boolean state = (stateStr != null && stateStr.equals("on"));
            course.setState(state ? true : false); // 使用数字1/0表示启用/禁用

            // 调用service层方法更新课程 - 修改为正确的方法名
            boolean updated = courseService.updateCourses(course);

            if (updated) {
                // 更新成功后重定向到课程管理页面并携带成功消息
                response.sendRedirect(request.getContextPath() + "/coursemanage/?success=" +
                        java.net.URLEncoder.encode("课程更新成功", "UTF-8"));
            } else {
                // 更新失败
                List<Subject> subjects = subjectService.findAllSubject();
                request.setAttribute("subjects", subjects);
                request.setAttribute("course", course);
                request.setAttribute("error", "课程更新失败");

                request.getRequestDispatcher("/WEB-INF/views/updatecourse.jsp").forward(request, response);
            }
        } catch (NumberFormatException e) {
            // ID或科目ID格式错误
            System.out.println("ID转换失败: " + courseIdStr + " 或 " + subjectId);

            List<Subject> subjects = subjectService.findAllSubject();
            request.setAttribute("subjects", subjects);
            request.setAttribute("error", "ID格式不正确");

            // 重新获取课程信息并设置到request中
            if (courseIdStr != null && !courseIdStr.trim().isEmpty()) {
                try {
                    int courseId = Integer.parseInt(courseIdStr);
                    Course existingCourse = courseService.findById(courseId);
                    if (existingCourse != null) {
                        request.setAttribute("course", existingCourse);
                    }
                } catch (NumberFormatException ex) {
                    // 忽略错误
                }
            }

            request.getRequestDispatcher("/WEB-INF/views/updatecourse.jsp").forward(request, response);
        }
    }

    /**
     * 处理课程排序保存
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void saveCourseSort(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");

            // 获取排序后的课程ID列表
            String courseOrder = request.getParameter("courseOrder");

            System.out.println("接收到的排序数据: " + courseOrder);

            if (courseOrder != null && !courseOrder.isEmpty()) {
                // 解析JSON数组
                String cleanOrder = courseOrder.replace("[", "").replace("]", "");
                if (!cleanOrder.trim().isEmpty()) {
                    String[] courseIds = cleanOrder.split(",");

                    if (courseIds.length > 0) {
                        List<Course> courseList = new ArrayList<>();
                        for (String id : courseIds) {
                            try {
                                Course course = new Course();
                                course.setId(Integer.parseInt(id.trim()));
                                courseList.add(course);
                            } catch (NumberFormatException e) {
                                System.err.println("无效的课程ID格式: " + id);
                            }
                        }

                        // 调用service层方法保存排序
                        if (!courseList.isEmpty()) {
                            boolean success = courseService.saveCourseBySort(courseList);

                            if (success) {
                                // 获取返回页面的参数
                                String subjectSearchText = (String) request.getSession().getAttribute("sortReturnSubjectSearchText");
                                String courseSearchText = (String) request.getSession().getAttribute("sortReturnCourseSearchText");
                                String pageIndex = (String) request.getSession().getAttribute("sortReturnPageIndex");

                                // 构建返回URL
                                StringBuilder returnUrl = new StringBuilder(request.getContextPath() + "/coursemanage/?success=" +
                                        java.net.URLEncoder.encode("课程排序保存成功", "UTF-8"));

                                boolean hasParams = true; // 已经有success参数了

                                if (subjectSearchText != null && !subjectSearchText.trim().isEmpty()) {
                                    if (hasParams) {
                                        returnUrl.append("&");
                                    } else {
                                        returnUrl.append("?");
                                        hasParams = true;
                                    }
                                    returnUrl.append("subjectSearchText=").append(java.net.URLEncoder.encode(subjectSearchText.trim(), "UTF-8"));
                                }

                                if (courseSearchText != null && !courseSearchText.trim().isEmpty()) {
                                    if (hasParams) {
                                        returnUrl.append("&");
                                    } else {
                                        returnUrl.append("?");
                                        hasParams = true;
                                    }
                                    returnUrl.append("courseSearchText=").append(java.net.URLEncoder.encode(courseSearchText.trim(), "UTF-8"));
                                }

                                if (pageIndex != null && !pageIndex.trim().isEmpty()) {
                                    if (hasParams) {
                                        returnUrl.append("&");
                                    } else {
                                        returnUrl.append("?");
                                        hasParams = true;
                                    }
                                    returnUrl.append("pageIndex=").append(pageIndex);
                                }

                                // 清理session中的参数
                                request.getSession().removeAttribute("sortReturnSubjectSearchText");
                                request.getSession().removeAttribute("sortReturnCourseSearchText");
                                request.getSession().removeAttribute("sortReturnPageIndex");

                                // 返回JSON格式的成功响应，包含返回URL
                                response.getWriter().write("{\"success\":true,\"message\":\"课程排序保存成功\",\"returnUrl\":\"" + returnUrl.toString() + "\"}");
                                return;
                            } else {
                                // 返回JSON格式的失败响应
                                response.getWriter().write("{\"success\":false,\"message\":\"课程排序保存失败\"}");
                                return;
                            }
                        } else {
                            response.getWriter().write("{\"success\":false,\"message\":\"没有有效的课程ID\"}");
                            return;
                        }
                    }
                }
            }

            response.getWriter().write("{\"success\":false,\"message\":\"没有课程需要排序\"}");
        } catch (Exception e) {
            System.err.println("保存课程排序时发生错误: " + e.getMessage());
            e.printStackTrace();
            try {
                response.getWriter().write("{\"success\":false,\"message\":\"保存排序失败: " + e.getMessage() + "\"}");
            } catch (Exception ex) {
                System.err.println("发送错误响应时发生异常: " + ex.getMessage());
            }
        } finally {
            try {
                response.getWriter().flush();
            } catch (Exception e) {
                // 忽略刷新异常
            }
        }
    }


    /**
     * 显示课程排序页面
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void showSortCourse(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取搜索参数
            String subjectSearchText = request.getParameter("subjectSearchText");
            String courseSearchText = request.getParameter("courseSearchText");
            String pageIndex = request.getParameter("pageIndex");

            System.out.println("进入showSortCourse方法");
            System.out.println("subjectSearchText: " + subjectSearchText);
            System.out.println("courseSearchText: " + courseSearchText);
            System.out.println("pageIndex: " + pageIndex);

            // 只有在搜索了专业的情况下才允许排序
            if (subjectSearchText == null || subjectSearchText.trim().isEmpty()) {
                // 如果没有搜索专业，重定向回课程管理页面
                System.out.println("没有专业搜索参数，重定向到课程管理页面");
                response.sendRedirect(request.getContextPath() + "/coursemanage/");
                return;
            }

            // 将搜索参数保存到session中，用于排序完成后跳转
            request.getSession().setAttribute("sortReturnSubjectSearchText", subjectSearchText);
            if (courseSearchText != null && !courseSearchText.trim().isEmpty()) {
                request.getSession().setAttribute("sortReturnCourseSearchText", courseSearchText);
            } else {
                request.getSession().removeAttribute("sortReturnCourseSearchText");
            }
            if (pageIndex != null && !pageIndex.trim().isEmpty()) {
                request.getSession().setAttribute("sortReturnPageIndex", pageIndex);
            } else {
                request.getSession().removeAttribute("sortReturnPageIndex");
            }

            List<Course> courses = new ArrayList<>();

            // 只按专业名称搜索
            subjectSearchText = subjectSearchText.trim();
            System.out.println("按专业搜索课程: " + subjectSearchText);
            courses = courseService.findSelectBySubjectName(subjectSearchText);
            System.out.println("查询到的课程数量: " + (courses != null ? courses.size() : "null"));

            // 确保courses不为null
            if (courses == null) {
                courses = new ArrayList<>();
            }

            request.setAttribute("courses", courses);
            request.setAttribute("subjectSearchText", subjectSearchText);

            List<Subject> subjects = subjectService.findAllSubject();
            System.out.println("获取到的专业数量: " + (subjects != null ? subjects.size() : "null"));
            // 确保subjects不为null
            if (subjects == null) {
                subjects = new ArrayList<>();
            }
            request.setAttribute("subjects", subjects);

            request.getRequestDispatcher("/WEB-INF/views/sortcourses.jsp").forward(request, response);
        } catch (Exception e) {
            System.err.println("加载课程排序页面时发生错误: " + e.getMessage());
            e.printStackTrace();
            request.setAttribute("error", "加载页面失败: " + e.getMessage());
        }
    }


    /**
     * 添加JSON字符串转义方法
     * @param str
     * @return
     */
    private String escapeJsonString(String str) {
        if (str == null) return "";
        return str.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }

    /**
     * 添加老师到课程
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void addTeacherToCourse(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");

            String courseIdStr = request.getParameter("courseId");
            String teacherIdStr = request.getParameter("teacherId");

            if (courseIdStr != null && !courseIdStr.trim().isEmpty() &&
                    teacherIdStr != null && !teacherIdStr.trim().isEmpty()) {

                try {
                    int courseId = Integer.parseInt(courseIdStr);
                    int teacherId = Integer.parseInt(teacherIdStr);

                    // 调用service层方法添加老师到课程
                    boolean success = courseService.setCourseTeacher(courseId, teacherId);

                    if (success) {
                        response.getWriter().write("{\"success\":true,\"message\":\"添加老师成功\"}");
                    } else {
                        response.getWriter().write("{\"success\":false,\"message\":\"添加老师失败\"}");
                    }
                } catch (NumberFormatException e) {
                    response.getWriter().write("{\"success\":false,\"message\":\"参数格式错误\"}");
                }
            } else {
                response.getWriter().write("{\"success\":false,\"message\":\"请选择课程和老师\"}");
            }
        } catch (Exception e) {
            System.err.println("添加老师到课程时发生错误: " + e.getMessage());
            e.printStackTrace();
            response.getWriter().write("{\"success\":false,\"message\":\"操作失败: " + e.getMessage() + "\"}");
        }
    }

    /**
     * 从课程中移除老师
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void removeCourseTeacher(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");

            String courseIdStr = request.getParameter("courseId");
            String teacherIdStr = request.getParameter("teacherId");

            if (courseIdStr != null && !courseIdStr.trim().isEmpty() &&
                    teacherIdStr != null && !teacherIdStr.trim().isEmpty()) {

                try {
                    int courseId = Integer.parseInt(courseIdStr);
                    int teacherId = Integer.parseInt(teacherIdStr);

                    // 调用service层方法从课程中移除老师
                    boolean success = courseService.removeTeacherFromCourse(teacherId, courseId);

                    if (success) {
                        response.getWriter().write("{\"success\":true,\"message\":\"移除老师成功\"}");
                    } else {
                        response.getWriter().write("{\"success\":false,\"message\":\"移除老师失败\"}");
                    }
                } catch (NumberFormatException e) {
                    response.getWriter().write("{\"success\":false,\"message\":\"参数格式错误\"}");
                }
            } else {
                response.getWriter().write("{\"success\":false,\"message\":\"参数不完整\"}");
            }
        } catch (Exception e) {
            System.err.println("从课程中移除老师时发生错误: " + e.getMessage());
            e.printStackTrace();
            response.getWriter().write("{\"success\":false,\"message\":\"操作失败: " + e.getMessage() + "\"}");
        }
    }

    /**
     * 获取课程已分配的老师列表（返回JSON）
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void getCourseTeachers(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");

            String courseIdStr = request.getParameter("courseId");

            if (courseIdStr != null && !courseIdStr.trim().isEmpty()) {
                try {
                    int courseId = Integer.parseInt(courseIdStr);

                    // 获取课程的老师
                    List<Teacher> teachers = courseService.findCourseByTeacher(courseId);

                    // 构建JSON响应（不包含email字段）
                    StringBuilder json = new StringBuilder("[");
                    if (teachers != null && !teachers.isEmpty()) {
                        for (int i = 0; i < teachers.size(); i++) {
                            Teacher teacher = teachers.get(i);
                            if (i > 0) {
                                json.append(",");
                            }
                            json.append("{")
                                    .append("\"id\":").append(teacher.getId()).append(",")
                                    .append("\"name\":\"").append(escapeJsonString(teacher.getName())).append("\"")
                                    .append("}");
                        }
                    }
                    json.append("]");

                    response.getWriter().write(json.toString());
                } catch (NumberFormatException e) {
                    response.getWriter().write("[]");
                }
            } else {
                response.getWriter().write("[]");
            }
        } catch (Exception e) {
            System.err.println("获取课程老师时发生错误: " + e.getMessage());
            e.printStackTrace();
            response.getWriter().write("[]");
        }
    }

    /**
     * 获取可分配给课程的老师列表（返回JSON）
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void getAvailableTeachers(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");

            // 直接获取所有老师
            List<Teacher> allTeachers = courseService.findAllTeachers();

            // 构建JSON响应
            StringBuilder json = new StringBuilder("[");
            if (allTeachers != null && !allTeachers.isEmpty()) {
                for (int i = 0; i < allTeachers.size(); i++) {
                    Teacher teacher = allTeachers.get(i);
                    if (i > 0) {
                        json.append(",");
                    }
                    json.append("{")
                            .append("\"id\":").append(teacher.getId()).append(",")
                            .append("\"name\":\"").append(escapeJsonString(teacher.getName())).append("\"")
                            .append("}");
                }
            }
            json.append("]");

            response.getWriter().write(json.toString());
        } catch (Exception e) {
            System.err.println("获取所有老师时发生错误: " + e.getMessage());
            e.printStackTrace();
            response.getWriter().write("[]");
        }
    }


}
